SpringMVC框架(6) —— 异常处理

项目结构

  • java
    • controller
      • TestException.java(Java文件)
    • exception
      • ExceptionController.java(Java文件)
      • TestExceptionResolver.java(Java文件)
  • resources
    • springmvc.xml(springmvc配置文件)
  • webapp
    • WEB-INF
      • pages
        • error.jsp(web页面)
      • web.xml(web配置文件)
    • index.jsp(web页面)
  • pom.xml(maven项目配置文件)

maven项目配置文件

  • 配置maven项目需要的依赖
    • spring-context
    • spring-web
    • spring-webmvc
    • servlet-api
    • jsp-api

web配置文件

  • 前端控制器(DispatcherServlet)
    • 配置一个前端控制器(<servlet>)
      • 创建前端控制器时,加载Spring配置文件(<init-param>)
      • 启动服务器时,创建前端控制器(<\load-on-startup>)
    • 配置前端控制器的作用范围(<servlet-mapping>)
  • 过滤器(CharacterEncodingFilter)
    • 配置一个过滤器(<filter>)
      • 配置编码(<init-param>):解决中文乱码
    • 配置前端控制器的作用范围(<filter-mapping>)

springmvc配置文件

  • 导入名称空间(<beans xmlns=””>)
  • 开启注解扫描(<context:component-scan base-package=””>)
  • 配置视图解析器(InternalResourceViewResolver)
    • 配置前缀(prefix -> “/WEB-INF/pages”)
    • 配置后缀(suffix -> “.jsp”)
  • 配置异常处理器(TestExceptionResolver)
  • 开启SpringMVC注解支持(<mvc:annotation-driven>)

Java文件

  • 表现层
      • 添加进IoC核心容器(@Controller)
      • 设置请求映射(@RequestMapping())
        • 一级目录(path=””)
        • 设置允许访问的请求方法(method=””)
        • 设置必需的参数和参数值(params=””)
          • 设置必需的请求头(headers=””)
    • 方法
      • 设置请求映射(@RequestMapping())
        • 二级目录(path=””)
      • 返回值(return “success”;)

JSP文件

  • 超链接(href=”一级目录/二级目录?请求参数=值&请求参数=值”)

执行代码

  • 需求:在index.jsp页面,点击的超链接,跳转到error.jsp页面,并且在页面输出响应消息

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.water</groupId>
<artifactId>section04_Exception</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>section04_Exception Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<!-- 版本锁定 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>

<!-- 依赖注入 -->
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<finalName>section04_Exception</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!-- 【filter】 -->
<filter>
<!-- 创建过滤器 -->
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 配置编码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 映射 -->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 【servlet】 -->
<servlet>
<!-- 创建DispatcherServlet -->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 创建DispatcherServlet时,加载spring配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器时,创建DispatcherServlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.water"/>


<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 配置异常处理器 -->
<bean id="testExceptionResolver" class="cn.water.exception.TestExceptionResolver"></bean>

<!-- 开启springMVC框架注解支持 -->
<mvc:annotation-driven/>


</beans>

ExceptionController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.water.controller;

import cn.water.exception.TestException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
* @author Water 自定义异常类
* @date 2019/10/3 - 19:47
*/
@Controller
@RequestMapping("/exception")
public class ExceptionController {


@RequestMapping("/test01")
public String test01() throws TestException{
System.out.println("方法执行了");
try {
int error = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new TestException("出现TestException错误!");
}

return "success";
}

}

index.jsp

1
2
3
4
5
6
7
8
9
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2><a href="exception/test01/">异常处理</a></h2>
</body>
</html>

error.jsp

1
2
3
4
5
6
7
8
9
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>${errorMessage}</h2>
</body>
</html>

异常处理

  • 当Controller类出现异常时
1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping("/test01")
public String test01() throws TestException{
System.out.println("方法执行了");
try {
int error = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new TestException("出现TestException错误!");
}

return "success";
}
  • 自定义异常类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cn.water.exception;

public class TestException extends Exception {

/* 存储提示信息 */
private String message;

/* Getter */
@Override
public String getMessage() {
return message;
}
/* Setter */
public void setMessage(String message) {
this.message = message;
}

/* 构造方法(提供提示信息) */
public TestException(String message) {
this.message = message;
}
}
  • 自定义异常处理器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cn.water.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Water 自定义异常处理器
* @date 2019/10/3 - 20:01
*/
public class TestExceptionResolver implements HandlerExceptionResolver {

@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

/* 判断异常对象 */
TestException te = null;
if (e instanceof TestException) {
te = (TestException)e;
}else {
te = new TestException("出现未知错误!");
}

/* 创建ModelAndView对象 */
ModelAndView mv = new ModelAndView();
/* 存储键值对 */
mv.addObject("errorMessage", te.getMessage());
/* 跳转到 error.jsp 页面 */
mv.setViewName("error");

/* 返回 */
return mv;
}
}
  • 配置异常处理器
1
2
 <!-- 配置异常处理器 -->
<bean id="testExceptionResolver" class="cn.water.exception.TestExceptionResolver"></bean>
-------------本文结束-------------
Donate comment here